// index.js
// 获取应用实例
import { wxRequest } from "../../utils/httpRequest"
import { getDistance, sortBy } from "../../utils/util"

const app = getApp()

Page({
  data: {
    inputSearchValue: '',
    latitude: 0,
    longitude: 0,
    sortItem: [
        {
            id: 1,
            name: "好评排序",
            ifChoose: false
        },
        {
            id: 2,
            name: "距离排序",
            ifChoose: false
        },
        {
            id: 3,
            name: "销量排序",
            ifChoose: false
        },
        {
            id: 4,
            name: "价格排序",
            ifChoose: false
        }
    ],
    receiveSort: [
        {
            id: 1,
            value: 4,
            name: "四星以上",
            ifChoose: false
        },
        {
            id: 2,
            value: 3,
            name: "三星以上",
            ifChoose: false
        },
        {
            id: 3,
            value: 0,
            name: "全部评分",
            ifChoose: true
        }
    ],
    distanceSort: [
      {
        id: 1,
        value: 2,
        name: "2km",
        ifChoose: false
      },
      {
        id: 2,
        value: 3,
        name: "3km",
        ifChoose: false
      },
      {
        id: 3,
        value: 4,
        name: "4km",
        ifChoose: true
      }
    ],
    salesSort: [
      {
        id: 1,
        value: 100,
        name: "100以上",
        ifChoose: false
      },
      {
        id: 2,
        value: 1000,
        name: "1000以上",
        ifChoose: false
      },
      {
        id: 3,
        value: 0,
        name: "全部",
        ifChoose: true
      }
    ],
    priceSort: [0, 1000],
    showSortMenu: false,
    shopList: [],
    allShopList: "",
    filterShopList: [],
    nowPage: 1,
    showMoreLoading: false,
    userInfo: {},
    hasUserInfo: false,
    getUserInfoShow: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  goSearch() {
    wx.navigateTo({
      url: `/home_package/search/search`,
    })
  },
  // 改变筛选界面里每个属性的选项
  changeFilterChoose (event) {
    var transition = this.data[event.currentTarget.dataset.filteritem].map((item) => {
      if (item.id.toString() == event.currentTarget.dataset.chooseid) {
        item.ifChoose = true;
      } else {
        item.ifChoose = false;
      }
      return item;
    });
    if(event.currentTarget.dataset.filteritem == "receiveSort") {
      this.setData({ receiveSort: transition });
    }
    if(event.currentTarget.dataset.filteritem == "distanceSort") {
      this.setData({ distanceSort: transition });
    }
    if(event.currentTarget.dataset.filteritem == "salesSort") {
      this.setData({ salesSort: transition });
    }
  },
  // 改变排序方式
  changeSortChoose (event) {
    let flag = false;
    var transition = this.data.sortItem.map((item) => {
        if (item.id.toString() == event.currentTarget.dataset.chooseid) {
          if(!item.ifChoose) {
              flag = true;
          }
          item.ifChoose = !item.ifChoose;
        } else {
          item.ifChoose = false;
        }
        return item;
    });
    if(flag) {
        let list = []
        if(event.currentTarget.dataset.chooseid == "1") {
            list = this.data.filterShopList.sort(sortBy("rate"))
        } else if(event.currentTarget.dataset.chooseid == "2") {
            list = this.data.filterShopList.sort(sortBy("distance")).reverse()
        } else if(event.currentTarget.dataset.chooseid == "3") {
            list = this.data.filterShopList.sort(sortBy("sales"))
        } else if(event.currentTarget.dataset.chooseid == "4") {
            list = this.data.filterShopList.sort(sortBy("avgPrice"))
        }
        this.setData({ filterShopList: list })
        let pageList = list.filter((item, index) => index < 20);
        this.setData({ nowPage: 1 }); 
        this.setData({ shopList: pageList });
    } else {
        this.changeFilter();
    }
    this.setData({ sortItem: transition });
  },
  // 价格区间的双滑块
  sliderChange(event) {
    this.setData({
      priceSort: event.detail.value,
    });
  },
  // 初始化筛选条件
  clearFilter() {
    var transition1 = [
        {
            id: 1,
            value: 4,
            name: "四星以上",
            ifChoose: false
        },
        {
            id: 2,
            value: 3,
            name: "三星以上",
            ifChoose: false
        },
        {
            id: 3,
            value: 0,
            name: "全部评分",
            ifChoose: true
        }
    ]
    this.setData({ receiveSort: transition1 });
    var transition2 = [
        {
          id: 1,
          value: 2,
          name: "2km",
          ifChoose: false
        },
        {
          id: 2,
          value: 3,
          name: "3km",
          ifChoose: false
        },
        {
          id: 3,
          value: 4,
          name: "4km",
          ifChoose: true
        }
    ]
    this.setData({ distanceSort: transition2 });
    var transition3 = [
        {
          id: 1,
          value: 100,
          name: "100以上",
          ifChoose: false
        },
        {
          id: 2,
          value: 1000,
          name: "1000以上",
          ifChoose: false
        },
        {
          id: 3,
          value: 0,
          name: "全部",
          ifChoose: true
        }
    ]
    this.setData({ salesSort: transition3 });
    this.setData({
      priceSort: [0, 1000],
    });
  },
  search() {
    this.setData({ showSortMenu: !this.data.showSortMenu });
    this.changeFilter();
  },
  changeFilter() {
    let params = {
        receive: this.data.receiveSort.filter((item) => item.ifChoose)[0].value,
        distance: this.data.distanceSort.filter((item) => item.ifChoose)[0].value,
        sales: this.data.salesSort.filter((item) => item.ifChoose)[0].value,
        minPrice: this.data.priceSort[0],
        maxPrice: this.data.priceSort[1],
    }
    let list = JSON.parse(this.data.allShopList).filter((item) => 
            item.rate >= params.receive && 
            item.distance <= params.distance &&
            item.sales >= params.sales &&
            item.avgPrice >= params.minPrice &&
            item.avgPrice <= params.maxPrice
    )
    this.setData({ filterShopList: list })
    let pageList = list.filter((item, index) => index < 20);
    this.setData({ nowPage: 1 }); 
    this.setData({ shopList: pageList });
  },
  // 跳转到点餐页面
  goShopMeals(event) {
    wx.navigateTo({
        url: `/home_package/shopMeals/shopMeals?shopId=${event.currentTarget.dataset.shopid}`,
    })
  },
  getShopList() {
    let params = {
    //   receive: this.data.receiveSort.filter((item) => item.ifChoose)[0].id,
    //   distance: this.data.distanceSort.filter((item) => item.ifChoose)[0].id,
    //   sales: this.data.salesSort.filter((item) => item.ifChoose)[0].id,
    //   minPrice: this.data.priceSort[0],
    //   maxPrice: this.data.priceSort[1],
      latitude: this.data.latitude,
      longitude: this.data.longitude
    }
    wxRequest('getShopList', params).then((res) => {
        let list = JSON.parse(res.data);
        list.map((item) => {
            item.distance = getDistance(item.latitude, item.longitude, this.data.latitude, this.data.longitude);
            return item;
        });
        this.setData({ allShopList: JSON.stringify(list) });
        this.setData({ filterShopList: list });
        let pageList = list.filter((item, index) => index < 20);
        this.setData({ shopList: pageList });
    });
  },
  perfectUserInfo(userInfo) {
    let params = {
        userName: userInfo.nickName,
        userUrl: userInfo.avatarUrl
    }
    wxRequest('perfectUserInfo', params).then((res) => {
        console.log("成功完善个人信息");
    });
  },
  getUserInfo(event) {
    this.perfectUserInfo(event.detail.userInfo);
  },
  showMoreShop() {
    if(this.data.nowPage * 20 < this.data.filterShopList.length) {
        this.setData({ showMoreLoading: true }); 
        setTimeout(this.showMoreShopAction, 1000);
    }
  },
  showMoreShopAction() {
    if(this.data.showMoreLoading) {
        this.setData({ nowPage: this.data.nowPage + 1 }); 
        let pageList = this.data.filterShopList.filter((item, index) => index < 20 * this.data.nowPage);
        this.setData({ shopList: pageList });
        this.setData({ showMoreLoading: false }); 
    }
  },
  onLoad() {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res);
        if (res.errMsg === "login:ok") {
          wxRequest('getOpenid', { code: res.code }).then((res) => {
            wx.setStorageSync('token', res.data)
            if(res.message == "验证") {
                this.setData({getUserInfoShow: true})
            }       
            wx.getLocation({
                type: 'wgs84',
                success: (res)=> {
                    this.setData({ latitude: res.latitude })
                    this.setData({ longitude: res.longitude })
                    this.getShopList();
                }
            })
          })
        }
      },
      fail: function (error) {
        console.log(error);
      }
    })
  }
})
